# @Time    : 2024/3/1 22:23
# @Author  : 🍁
# @File    : dashboard.py
# @Software: PyCharm
import collections
import datetime
import time

from django.views import View
from django import http
from django.shortcuts import render
from django.db.models import Count

from web import models


class DashboardView(View):
    def get(self, request, project_id):
        # 问题的数据处理
        issues_dict = collections.OrderedDict()
        for key, text in models.Issues.status_choices:
            issues_dict[key] = {"text": text, "count": 0}
        # 根据status 进行分组，并以id统计数量
        status_count = models.Issues.objects.filter(project_id=project_id).values("status").annotate(ct=Count("id"))
        for item in status_count:
            issues_dict[item["status"]]["count"] = item["ct"]

        # 项目参与者
        project_join = models.UserProject.objects.filter(project_id=project_id).values("user_id", "user__username")

        # 项目动态
        top_ten = models.Issues.objects.filter(project_id=project_id, assign__isnull=False).order_by("-id")[0:10]
        context = {
            "issues_dict": issues_dict,
            "project_join": project_join,
            "top_ten": top_ten,
        }
        return render(request, "dashboard.html", context)


# 画图
class DashboardChartsView(View):
    def get(self, request, project_id):
        # 拿到今天的日期
        today = datetime.datetime.now().date()
        day_count_dict = {}
        for i in range(0, 30):
            date = today - datetime.timedelta(days=30 - i)
            day_count_dict[str(date)] = [time.mktime(date.timetuple()) * 1000, 0]
        # """
        # create_datetime__gte=today - datetime.timedelta(days=30)
        # 拿到30天之前日期的数据
        #
        # select={"ctime": "strftime(%%Y-%%m-%%d, issues.create_datetime)"} sqlite 语法里面的函数strftime
        # select={"ctime": "DATE_FORMAT(issues.create_datetime, %%Y-%%m-%%d)"} mysql 语法里面的函数DATE_FORMAT
        # trftime(%%Y-%%m-%%d, issues.create_datetime) 查询时间为xx年xx月xx日 的时间，并新建一列查询，列名为ctime
        # select id, name, strftime(%%Y-%%m-%%d, issues.create_datetime) as ctime
        # """
        day_count = models.Issues.objects.filter(project_id=project_id,
                                                 create_datetime__gte=today - datetime.timedelta(days=30)
                                                 ).extra(
            select={"ctime": "DATE_FORMAT(issues.create_datetime, '%%Y-%%m-%%d')"}
        ).values("ctime").annotate(ct=Count("id"))

        for item in day_count:
            day_count_dict[item["ctime"]][1] = item["ct"]
        return http.JsonResponse({"status": True, "data": day_count_dict})
